package cn.orange.ch03_linked;

import cn.orange.ListNode;

/**
 * LC19.删除链表的倒数第 N 个结点
 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点
 */
public class LC19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1, head);
        ListNode prev = dummy, curr = dummy;
        while (n > 0) {
            curr = curr.next;
            n--;
        }
        while (curr.next != null) {
            curr = curr.next;
            prev = prev.next;
        }
        prev.next = prev.next.next;
        return dummy.next;
    }
    public static void main(String[] args) {
        LC19 alg = new LC19();
        ListNode h1 = new ListNode(1, new ListNode(2, new ListNode(6, new ListNode(4, new ListNode(5, new ListNode(6))))));
        System.out.println(alg.removeNthFromEnd(h1, 2));
        ListNode h2 = new ListNode(1, new ListNode(2, new ListNode(3)));
        System.out.println(alg.removeNthFromEnd(h2, 1));
        ListNode h3 = new ListNode(1);
        System.out.println(alg.removeNthFromEnd(h3, 1));
    }
}
